<template>
  <div>
    <Form ref="form" :model="formItem" :label-width="100">
      <FormItem prop="expireTime" label="过期时间">
        <Badge v-if="formItem.isExpired" text="授权已过期">
          <DatePicker
            v-model="formItem.expireTime"
            class="ivu-form-item-error"
            type="datetime"
            placeholder="授权有效期"></DatePicker>
        </Badge>
        <DatePicker v-else="" v-model="formItem.expireTime" type="datetime" placeholder="设置有效期"></DatePicker>
      </FormItem>
      <FormItem prop="authorities" label="接口授权">
        <Transfer
          :data="selectApis"
          :list-style="{width: '45%',height: '480px'}"
          :titles="['选择授权接口', '已授权接口']"
          :render-format="transferRender"
          :target-keys="formItem.authorities"
          @on-change="handleTransferChange"
          filterable>
        </Transfer>
      </FormItem>
    </Form>
  </div>
</template>

<script>

export default {
  name: 'AppAuth',
  data () {
    return {
      selectApis: [],
      formItem: this.getFormItem()
    }
  },
  methods: {
    getFormItem () {
      return {
        appId: '',
        authorities: [],
        expireTime: '',
        isExpired: false
      }
    },
    /* 初始数据 */
    setData (data) {
      if (data && data.appId) {
        Object.assign(this.formItem, {
          appId: data.appId
        })
        this.handleLoadAppGranted(data.appId)
      }
    },
    handleReset () {
      this.$refs['form'].resetFields()
      this.formItem = this.getFormItem()
    },
    /* 提交授权 */
    handleSubmit () {
      return new Promise((resolve, reject) => {
        this.$refs['form'].validate((valid) => {
          if (valid) {
            this.$http.post(this.$apis.authority.appGrant, {
              appId: this.formItem.appId,
              expireTime: this.formItem.expireTime ? this.formItem.expireTime.pattern('yyyy-MM-dd HH:mm:ss') : '',
              authorityIds: this.formItem.authorities.join(',')
            }).then(res => {
              resolve(res)
            }).catch(function (err) {
              reject(err)
            })
          } else {
            resolve(false)
          }
        })
      })
    },
    handleLoadAppGranted (appId) {
      if (!appId) {
        return
      }
      const that = this
      const p1 = this.$http.get(this.$apis.authority.api, {}, this)
      const p2 = this.$http.get(this.$apis.authority.app, { appId: appId }, this)
      Promise.all([p1, p2]).then(function (values) {
        const res1 = values[0]
        const res2 = values[1]
        if (res1.code === 0) {
          res1.data.map(item => {
            item.key = item.authorityId
            item.label = `${item.prefix.replace('/**', '')}${item.path} - ${item.apiName}`
            item.disabled = item.path === '/**'
          })
          that.selectApis = res1.data
        }
        if (res2.code === 0) {
          const authorities = []
          res2.data.map(item => {
            if (item.authority.indexOf('APP_') === -1 && !authorities.includes(item.authorityId)) {
              authorities.push(item.authorityId)
            }
          })
          that.formItem.authorities = authorities
          // 时间
          if (res2.data.length > 0) {
            that.formItem.expireTime = res2.data[0].expireTime
            that.formItem.isExpired = res2.data[0].isExpired
          }
        }
        that.modalVisible = true
      })
    },
    transferRender (item) {
      return `<span  title="${item.label}">${item.label}</span>`
    },
    handleTransferChange (newTargetKeys, direction, moveKeys) {
      if (newTargetKeys.indexOf('1') != -1) {
        this.formItem.authorities = ['1']
      } else {
        this.formItem.authorities = newTargetKeys
      }
    },
    mounted: function () {
    }
  }
}
</script>
